package com.sos.activity;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import android.location.Location;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.GeoPoint;
import com.baidu.mapapi.LocationListener;
import com.baidu.mapapi.MKAddrInfo;
import com.baidu.mapapi.MKDrivingRouteResult;
import com.baidu.mapapi.MKLocationManager;
import com.baidu.mapapi.MKPoiResult;
import com.baidu.mapapi.MKSearch;
import com.baidu.mapapi.MKSearchListener;
import com.baidu.mapapi.MKTransitRouteResult;
import com.baidu.mapapi.MKWalkingRouteResult;
import com.baidu.mapapi.MapActivity;
import com.baidu.mapapi.MapView;
import com.baidu.mapapi.MyLocationOverlay;
import com.sos.R;
import com.sos.service.CameraService;
import com.sos.service.LactionService;
import com.sos.service.SMSService;
import com.sos.service.SetManager;
import com.sos.service.WWWService;
import com.sos.util.HttpUtil;
import com.sos.vo.SetInfo;
import com.sos.vo.SosInfo;

/**
 * 主界面
 *  百度地图文档：
 *  
 * http://dev.baidu.com/wiki/imap/index.php?title=Android%E5%B9%B3%E5
 * %8F%B0/%E5%BC%80%E5%8F%91%E6%8C%87%E5%8D%97
 * 百度地图类参考
 * http://dev.baidu.com/wiki/imap/index.php?title=Android%E5%B9%B3%E5%8F%B0/%E7%B1%BB%E5%8F%82%E8%80%83
 * **/
public class MainActivity extends MapActivity {
	/** Called when the activity is first created. */
	private final static String TAG = MainActivity.class.getSimpleName();

	private ImageView camImg;// 拍照结果图片
	// 菜单
	private final static int MENU_CAM = 0;// 拍照
	private final static int MENU_LOCATION = 1;// 位置
	private final static int MENU_SMS = 3;// 短信
	private final static int MENU_MMS = 4;// 彩信
	private final static int MENU_EMAIL = 5;// 邮件
	private final static int MENU_MAP = 6;// 地图菜单
	private final static int MENU_ADDCON = 7;// 添加联系人
	private final static int MENU_WWW = 8;// 网站求救
	private final static int MENU_SET = 9;// 系统设置

	// 地址文本框
	private EditText loactionEdit;// 位置信息
	private EditText emailEdit;// 邮件
	private EditText phoneEdit;// 电话
	private EditText sosEdit;// 求救内容
	private EditText nameEdit;// 求助人
	Location lo;

	private LactionService locService;// 位置服务类实例
	private SMSService smsService;// 短息服务类实例
	private CameraService camService;// 照相服务类
	WWWService www = new WWWService(MainActivity.this);
	SosInfo sosinfo = new SosInfo();
	String lcores = "", lat = "", lon = "";

	SetManager setManager;
	SetInfo setinfo = new SetInfo();
	String ip = "192.168.0.1";
	String port = "8080";
	String ret = "";

	// 百度地图，详细请看百度地图文档
	BMapManager mBMapMan = null;
	MapView mMapView = null;
	MKLocationManager mLocationManager = null;// 地图位置管理
	MyLocationOverlay mLocationOverlay = null; // 定位图层
	LocationListener mLocationListener;// 位置监听器
	Button jietuBtn;// 地图截图按钮
	MKSearch mSearch = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		Log.d(TAG, "oncreate");
		camImg = (ImageView) findViewById(R.id.camImg);
		loactionEdit = (EditText) findViewById(R.id.locationEdit);
		nameEdit = (EditText) findViewById(R.id.name);
		// locationMap=(MapView) findViewById(R.id.locationMap);
		sosEdit = (EditText) findViewById(R.id.sosEdit);
		emailEdit = (EditText) findViewById(R.id.emailEdit);
		phoneEdit = (EditText) findViewById(R.id.phoneEdit);
		jietuBtn = (Button) findViewById(R.id.jietuBtn);
		jietuBtn.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				jietu();
			}
		});
		locService = new LactionService(this);
		smsService = new SMSService(this);
		camService = new CameraService(this);
		setManager = new SetManager(this);

		setinfo = setManager.get();// 读取系统设置信息

		emailEdit.setText(setinfo.getDefalut_email());
		phoneEdit.setText(setinfo.getSos_phone());
		nameEdit.setText(setinfo.getMy_name());
		ip = setinfo.getWww_ip();
		port = setinfo.getWww_port();
		// 地图
		// 在地图Activity中定义变量： BMapManager mBMapMan = null;
		// 在onCreate方法中增加以下代码，并将您申请的Key替换“我的Key”：

		mBMapMan = new BMapManager(getApplication());
		mBMapMan.init("85757CB713ACD9CB1497D2FAA3B3C6A8CAA6DC85", null);
		super.initMapActivity(mBMapMan);
		// 初始化Location模块
		mLocationManager = mBMapMan.getLocationManager();
		mMapView = (MapView) findViewById(R.id.bmapsView);
		mMapView.setBuiltInZoomControls(true); // 设置启用内置的缩放控件
		mMapView.setBuiltInZoomControls(true);
		// 设置在缩放动画过程中也显示overlay,默认为不绘制
		mMapView.setDrawOverlayWhenZooming(true);
		/**
		 * 
		 * 地图覆盖物概述
		 * 
		 * 所有叠加或覆盖到地图的内容，我们统称为地图覆盖物。如标注、矢量图形元素(包括：折线和多边形和圆)、定位图标等。覆盖物拥有自己的地理坐标，
		 * 当您拖动或缩放地图时，它们会相应的移动。
		 * 
		 * 地图API提供了如下几种覆盖物：
		 * 
		 * Overlay：覆盖物的抽象基类，所有的覆盖物均继承此类的方法，实现用户自定义图层显示。
		 * MyLocationOverlay：一个负责显示用户当前位置的Overlay。 ItemizedOverlay<Item extends
		 * OverlayItem>：Overlay的一个基类，包含了一个OverlayItem列表，相当于一组分条的Overlay，通过继承此类，
		 * 将一组兴趣点显示在地图上。
		 * 
		 * PoiOverlay：本地搜索图层，提供某一特定地区的位置搜索服务，比如在北京市搜索“公园”，通过此图层将公园显示在地图上。
		 * 
		 * RouteOverlay：步行、驾车导航线路图层，将步行、驾车出行方案的路线及关键点显示在地图上。
		 * 
		 * TransitOverlay：公交换乘线路图层，将某一特定地区的公交出行方案的路线及换乘位置显示在地图上。
		 * 
		 * 
		 * **/
		mLocationOverlay = new MyLocationOverlay(this, mMapView);
		mLocationManager = mBMapMan.getLocationManager();
		mLocationManager.enableProvider(MKLocationManager.MK_NETWORK_PROVIDER);
		mLocationManager.disableProvider(MKLocationManager.MK_GPS_PROVIDER);
		mLocationOverlay.enableMyLocation(); // 启用定位
		mLocationOverlay.enableCompass(); // 启用指南针

		mMapView.getOverlays().add(mLocationOverlay);
		mSearch = new MKSearch();
		/****
		 * 
		 * 百度地图移动版API集成搜索服务包括：位置检索、周边检索、范围检索、公交检索、驾乘检索、步行检索，
		 * 通过初始化MKSearch类，注册搜索结果的监听对象MKSearchListener，实现异步搜索服务。
		 * 首先自定义MySearchListener实现MKSearchListener接口，通过不同的回调方法，获得搜索结果： 

		 * **/
		mSearch.init(mBMapMan, new MKSearchListener() {

			@Override
			public void onGetAddrResult(MKAddrInfo res, int arg1) {
				// TODO Auto-generated method stub

				Toast.makeText(MainActivity.this, res.strAddr,
						Toast.LENGTH_SHORT).show();
			}

			@Override
			public void onGetDrivingRouteResult(MKDrivingRouteResult arg0,
					int arg1) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onGetPoiResult(MKPoiResult arg0, int arg1, int arg2) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onGetTransitRouteResult(MKTransitRouteResult arg0,
					int arg1) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onGetWalkingRouteResult(MKWalkingRouteResult arg0,
					int arg1) {
				// TODO Auto-generated method stub

			}

		});
		/**
		 * 
		 * 定位监听 
实现方式与系统的定位监听类似，通过MKLocationManager注册或者移除定位监听器：

		 * ***/
		mLocationListener = new LocationListener() {

			@Override
			public void onLocationChanged(Location location) {
				if (location != null) {
					GeoPoint pt = new GeoPoint(
							(int) (location.getLatitude() * 1e6),
							(int) (location.getLongitude() * 1e6));
					mMapView.getController().animateTo(pt);
					mSearch.reverseGeocode(pt);
				}
			}
		};

	}

	// Override以下方法,管理API:

	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	protected void onDestroy() {
		if (mBMapMan != null) {
			mBMapMan.destroy();
			mBMapMan = null;
		}
		super.onDestroy();
	}

	@Override
	protected void onPause() {
		if (mBMapMan != null) {
			mBMapMan.getLocationManager().removeUpdates(mLocationListener);
			mBMapMan.stop();
		}
		super.onPause();
	}

	@Override
	protected void onResume() {
		if (mBMapMan != null) {
			mBMapMan.getLocationManager().requestLocationUpdates(
					mLocationListener);
			mBMapMan.start();
		}
		super.onResume();
	}

	/***
	 * 菜单
	 * **/
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		menu.add(0, MENU_CAM, 0, getString(R.string.cam_btn));//
		menu.add(0, MENU_LOCATION, 0, getString(R.string.location_btn));//
		menu.add(0, MENU_SMS, 0, getString(R.string.sms_btn));//
		menu.add(0, MENU_MMS, 0, getString(R.string.mms_btn));//
		menu.add(0, MENU_EMAIL, 0, getString(R.string.email_btn));//
		menu.add(0, MENU_MAP, 0, getString(R.string.map_btn));
		menu.add(0, MENU_ADDCON, 0, getString(R.string.add_con_btn));
		menu.add(0, MENU_WWW, 0, getString(R.string.www_btn));
		menu.add(0, MENU_SET, 0, getString(R.string.set));
		return super.onCreateOptionsMenu(menu);
	}

	/***
	 * 菜单事件
	 * */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		String subject = "求救";
		String phone = phoneEdit.getText().toString();
		String content = "电话：" + phoneEdit.getText() + "\n" + "地址："
				+ loactionEdit.getText() + "\n内容：" + sosEdit.getText();
		switch (item.getItemId()) {
		case MENU_CAM:// 拍照

			Intent intent = camService.camer("camera.jpg");
			startActivityForResult(intent, 0);
			return true;
		case MENU_LOCATION:// 获得位置

			getLocation();
			return true;
		case MENU_SMS:// 短信

			smsService.send(phone, content);
			return true;
		case MENU_MMS:// 彩信
			sendmms(subject, content, phone);
			return true;
		case MENU_EMAIL:// 邮件

			sendEmail(subject, content);

			return true;
		case MENU_MAP:// map截图
			// google 地图截图
			// Bitmap b = locationMap.getDrawingCache();
			// 百度地图截图

			jietu();

			return true;
		case MENU_ADDCON:// 添加联系人
			Intent add_intent = new Intent();
			add_intent
					.setClass(MainActivity.this, AddByContactorActivity.class);
			startActivityForResult(add_intent, 2);
			return true;
		case MENU_WWW:

			www();
			return true;
		case MENU_SET:
			Intent setIntent = new Intent();
			setIntent.setClass(this, SetActivity.class);
			startActivity(setIntent);
			return true;

		}
		return false;
	}

	/***
	 * 网站后台求助
	 * */
	public void www() {
		sosinfo.setSoAddress(loactionEdit.getText().toString());
		sosinfo.setSoLat(lat);
		sosinfo.setSoLon(lon);
		sosinfo.setSoName(setinfo.getMy_name());
		sosinfo.setSoUserPhone(setinfo.getMy_hone());
		Toast.makeText(MainActivity.this, "网站求助", Toast.LENGTH_SHORT).show();
		new Thread() {
			public void run() {
				ret = www.putSosInfo(ip, port, sosinfo);
				hadel.obtainMessage(1, ret).sendToTarget();
			}
		}.start();
	}

	/***
	 * email
	 * */
	public void sendEmail(String subject, String content) {
		String[] receiver = new String[] { emailEdit.getText() + "" };

		Uri ur = Uri.parse("file:///sdcard/camera.jpg");
		Intent email = new Intent(Intent.ACTION_SEND);

		// 设置邮件发收人
		email.putExtra(Intent.EXTRA_EMAIL, receiver);
		// 设置邮件标题
		email.putExtra(Intent.EXTRA_SUBJECT, subject);
		// 设置邮件内容
		email.putExtra(Intent.EXTRA_TEXT, content);
		// 附件
		email.putExtra(Intent.EXTRA_STREAM, ur);

		email.setType("image/jpg");
		// 调用系统的邮件系统
		Intent it = Intent.createChooser(email, "请选择邮件发送软件");
		startActivityForResult(it, 1);
	}

	/****
	 * 发彩信
	 * */
	public void sendmms(String subject, String content, String phone) {
		try {
			Log.d(TAG, "彩信yes");
			Class.forName("com.android.mms.ui.ComposeMessageActivity");
			Toast.makeText(MainActivity.this, "支持彩信", Toast.LENGTH_SHORT)
					.show();

			Intent mmsintent = new Intent(Intent.ACTION_SEND);
			mmsintent.setClassName("com.android.mms",
					"com.android.mms.ui.ComposeMessageActivity");
			mmsintent.putExtra("subject", subject);
			mmsintent.putExtra("sms_body", content);
			mmsintent.putExtra("address", phone);
			mmsintent.putExtra(Intent.EXTRA_STREAM,
					Uri.parse("file:///sdcard/camera.jpg"));
			mmsintent.setType("image/jpeg");
			startActivity(mmsintent);

		} catch (Exception e) {
			Log.d(TAG, "彩信no");
			// e.printStackTrace();
			StackTraceElement[] es = e.getStackTrace();
			for (StackTraceElement e1 : es) {
				Log.d(TAG, "彩信no:" + e1.toString());
			}
			Toast.makeText(MainActivity.this, e.getMessage(),
					Toast.LENGTH_SHORT).show();
			Toast.makeText(MainActivity.this, "不支持彩信", Toast.LENGTH_SHORT)
					.show();

		}
	}

	// 获得位置
	public void getLocation() {
		if (!HttpUtil.isNetWorkConnected(MainActivity.this)) {
			Toast.makeText(MainActivity.this, "网络不通，前检查网络配置", Toast.LENGTH_LONG)
					.show();
			// return true;
		} else {
			lo = locService.getLoca();
			if (lo != null) {
				lcores = locService.getAddress(lo.getLatitude() + ","
						+ lo.getLongitude());
				lat = lo.getLatitude() + "";
				lon = lo.getLongitude() + "";
				// lcores=lat+","+lon;
				Toast.makeText(MainActivity.this, lcores, Toast.LENGTH_LONG)
						.show();
				Log.d(TAG, "坐标：" + lcores);
				loactionEdit.setText(lcores);

			} else {
				Toast.makeText(MainActivity.this, "无法获得坐标", Toast.LENGTH_LONG)
						.show();
			}
		}
	}

	// 百度地图截图
	public void jietu() {
		mMapView.setDrawingCacheEnabled(true);
		mMapView.buildDrawingCache();
		Bitmap b = mMapView.getDrawingCache();

		int re = savePic(b, "sdcard/baidumap.png");
		if (re == 0) {
			Toast.makeText(MainActivity.this, "map截图成功", Toast.LENGTH_LONG)
					.show();
		} else {
			Toast.makeText(MainActivity.this, "map截图 失败", Toast.LENGTH_LONG)
					.show();
		}
	}

	Handler hadel = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			Toast.makeText(MainActivity.this, msg.what + "," + msg.obj,
					Toast.LENGTH_SHORT).show();
		}

	};

	/**
	 * 保存照片
	 * **/
	private int savePic(Bitmap b, String strFileName) {
		int ret = -1;
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(strFileName);
			if (null != fos) {
				if (null != b) {
					b.compress(Bitmap.CompressFormat.PNG, 90, fos);
					fos.flush();
					fos.close();
					ret = 0;
				}

			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			ret = 1;

		} catch (IOException e) {
			e.printStackTrace();
			ret = 2;
		}
		return ret;
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		Log.d(TAG, "onActivityResult" + requestCode + "resultCode");

		if (requestCode == 0) {
			Toast.makeText(MainActivity.this, "拍照成功", Toast.LENGTH_LONG).show();

			String pathString = Environment.getExternalStorageDirectory()
					.toString() + "/camera.jpg";
			Log.d(TAG, pathString);
			Bitmap b = BitmapFactory.decodeFile(pathString);
			camImg.setImageBitmap(b);

		} else if (requestCode == 2) {
			Toast.makeText(MainActivity.this, "添加电话号码成功！", Toast.LENGTH_LONG)
					.show();
			String name = data.getStringExtra("name");
			String phone = data.getStringExtra("phone");
			phoneEdit.setText(phone);
			nameEdit.setText(name);
			Log.i(TAG, "name:" + name + ",phone:" + phone);
		}

	}

}